package com.dzl.shoppingCart;

import com.dzl.base.controller.BaseController;
import com.dzl.shoppingCart.pojo.WelfareUserShoppingCart;
import com.dzl.shoppingCart.pojo.dto.WelfareUserShoppingCartDto;
import com.dzl.shoppingCart.pojo.query.WelfareUserShoppingCartQuery;
import com.dzl.shoppingCart.pojo.vo.WelfareUserShoppingCartSupplierListVo;
import com.dzl.shoppingCart.pojo.vo.WelfareUserShoppingCartSupplierVo;
import com.dzl.shoppingCart.pojo.vo.WelfareUserShoppingCartVo;
import com.dzl.shoppingCart.service.WelfareUserShoppingCartService;
import com.dzl.util.EmptyUtils;
import com.dzl.util.ImageUtils;
import com.dzl.util.JsonResult;
import com.dzl.util.PageUtils;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 小程序用户购物车(WelfareUserShoppingCart)表控制层
 * @author ChenLong
 * @since 2021-05-20 11:33:10
 */
@Slf4j
@RestController
@RequestMapping("welfareUserShoppingCart")
public class WelfareUserShoppingCartController extends BaseController {

    @Autowired
    private WelfareUserShoppingCartService welfareUserShoppingCartService;

    /**
     * 购物车数量限制
     */
    private Integer MAX_SHOPPING_CART_LIMIT = 99;

    /**
     * 删除购物车商品
     * @param id 行id
     * @return com.dzl.util.JsonResult<java.lang.Object>
     * @author ChenLong
     * @since 2021-05-20 15:23:25
     **/
    @DeleteMapping(value = "deleteCartGoodsById")
    public JsonResult<Integer> deleteCartGoodsById(Integer id) {
        log.info("deleteCartGoodsById in id: " + id);
        if (EmptyUtils.isEmpty(id)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        Integer userId = getWxUserInfo().getId();
        WelfareUserShoppingCart welfareUserShoppingCart = welfareUserShoppingCartService.selectByPrimaryKey(id);
        if (EmptyUtils.isNotEmpty(welfareUserShoppingCart) && !welfareUserShoppingCart.getUserId().equals(userId)) {
            return JsonResult.paramErrWithMsg("删除失败，无效用户");
        }
        if (welfareUserShoppingCartService.deleteById(id, userId)) {
            return JsonResult.success();
        } else {
            return JsonResult.failWithMsg("操作失败，请重试");
        }
    }

    /**
     * 删除购物车商品
     * @param ids 行id列表
     * @return com.dzl.util.JsonResult<java.lang.Object>
     * @author ChenLong
     * @since 2021-05-20 15:23:25
     **/
    @DeleteMapping(value = "deleteBatchCartGoodsByIdList")
    public JsonResult<Integer> deleteBatchCartGoodsByIdList(String ids) {
        log.info("deleteBatchCartGoodsByIdList in ids: " + ids);
        if (EmptyUtils.isEmpty(ids)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        Integer userId = getWxUserInfo().getId();
        String[] idListStr = ids.split(",");
        List<Integer> idList = new ArrayList<>();
        for (String s : idListStr) {
            Integer id = Integer.parseInt(s);
            idList.add(id);
        }
        if (welfareUserShoppingCartService.deleteBatchByIdList(idList, userId)) {
            return JsonResult.success();
        } else {
            return JsonResult.failWithMsg("操作失败，请重试");
        }
    }

    /**
     * 修改购物车商品数量
     * @param id       id
     * @param quantity 数量
     * @return com.dzl.util.JsonResult<java.lang.Object>
     * @author ChenLong
     * @date 2021-05-22 11:02:49
     **/
    @PostMapping(value = "updateCartGoodsQuantityById")
    public JsonResult<Integer> updateCartGoodsQuantityById(Integer id, Integer quantity) {
        log.info("updateCartGoodsQuantityById in id,quantity: " + id + "," + quantity);
        if (EmptyUtils.isEmpty(id)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        if (EmptyUtils.isEmpty(quantity)) {
            return JsonResult.paramErrWithMsg("参数错误");// 0走删除
        }
        Integer userId = getWxUserInfo().getId();
        WelfareUserShoppingCart welfareUserShoppingCart = new WelfareUserShoppingCart();
        welfareUserShoppingCart.setId(id);
        welfareUserShoppingCart.setUserId(userId);
        if (quantity > MAX_SHOPPING_CART_LIMIT) {
            welfareUserShoppingCart.setQuantity(MAX_SHOPPING_CART_LIMIT);
        } else {
            welfareUserShoppingCart.setQuantity(quantity);
        }
        welfareUserShoppingCart.setUpdateTime(new Date());
        if (welfareUserShoppingCartService.updateByPrimaryKeySelective(welfareUserShoppingCart) > 0) {
            return JsonResult.success();
        } else {
            return JsonResult.failWithMsg("操作失败");
        }
    }

    /**
     * 获取用户购物车商品信息
     * @param query 购物车查询实体类
     * @return com.dzl.util.PageUtils
     * @author ChenLong
     * @since 2021-05-20 15:23:43
     **/
    @GetMapping(value = "getUserCartGoodsListByPage")
    public PageUtils<WelfareUserShoppingCartVo> getUserCartGoodsListByPage(WelfareUserShoppingCartQuery query) {
        log.info("getUserCartGoodsListByPage in query: " + query);
        Integer userId = getWxUserInfo().getId();
        query.setUserId(userId);
        List<WelfareUserShoppingCartVo> welfareUserShoppingCartVoList = welfareUserShoppingCartService.getUserCartGoodsList(query);
        if (EmptyUtils.isNotEmpty(welfareUserShoppingCartVoList)) {
            welfareUserShoppingCartVoList.forEach(welfareUserShoppingCartVo -> {
                if (EmptyUtils.isNotEmpty(welfareUserShoppingCartVo.getGoodsImg())) {
                    welfareUserShoppingCartVo.setGoodsImg(ImageUtils.setImageSrc(welfareUserShoppingCartVo.getGoodsImg()));
                }
            });
        }
        PageInfo<WelfareUserShoppingCartVo> pageInfo = new PageInfo<>(welfareUserShoppingCartVoList);
        return new PageUtils<>(pageInfo);
    }

    /**
     * 获取用户购物车商品信息
     * @param ids 购物车查询实体类
     * @return com.dzl.util.PageUtils
     * @author ChenLong
     * @since 2021-05-20 15:23:43
     **/
    @GetMapping(value = "getUserCartGoodsListGroupBySupplierByIdList")
    public JsonResult<WelfareUserShoppingCartSupplierVo> getUserCartGoodsListGroupBySupplierByIdList(String ids,String area) {
        log.info("getUserCartGoodsListByPage in ids: " + ids);
        log.info("getUserCartGoodsListByPage in area: " + area);
        if (EmptyUtils.isEmpty(ids)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        String[] idListStr = ids.split(",");
        List<Integer> idList = new ArrayList<>();
        for (String s : idListStr) {
            Integer id = Integer.parseInt(s);
            idList.add(id);
        }
        return JsonResult.success(welfareUserShoppingCartService.getUserCartGoodsListGroupBySupplierByIdList(idList,area));
    }

    /**
     * 获取用户购物车商品信息
     * @param query 购物车查询实体类
     * @return com.dzl.util.PageUtils
     * @author ChenLong
     * @since 2021-05-20 15:23:43
     **/
    @GetMapping(value = "getUserCartGoodsListGroupBySupplier")
    public PageUtils<WelfareUserShoppingCartSupplierListVo> getUserCartGoodsListGroupBySupplier(WelfareUserShoppingCartQuery query) {
        log.info("getUserCartGoodsListByPage in query: " + query);
        Integer userId = getWxUserInfo().getId();
        query.setUserId(userId);
        List<WelfareUserShoppingCartSupplierListVo> welfareUserShoppingCartVoList = welfareUserShoppingCartService.getUserCartGoodsListGroupBySupplier(query);
        PageInfo<WelfareUserShoppingCartSupplierListVo> pageInfo = new PageInfo<>(welfareUserShoppingCartVoList);
        return new PageUtils<>(pageInfo);
    }

    /**
     * 添加商品到购物车
     * @param query 购物车查询实体类
     * @return com.dzl.util.JsonResult<java.lang.Object>
     * @author ChenLong
     * @since 2021-05-20 15:23:59
     **/
    @PostMapping(value = "addGoodsToCart")
    public JsonResult<Integer> addGoodsToCart(@RequestBody WelfareUserShoppingCartDto query) {
        log.info("addGoodsToCart in query: " + query);
        Integer userId = getWxUserInfo().getId();
        WelfareUserShoppingCart welfareUserShoppingCart = new WelfareUserShoppingCart();
        welfareUserShoppingCart.setUserId(userId);
        // 如果该用户下有相同规格商品，就增加数量，没有就添加商品
        WelfareUserShoppingCart welfareUserShoppingCartSelect = new WelfareUserShoppingCart();
        welfareUserShoppingCartSelect.setStatus(1);
        welfareUserShoppingCartSelect.setUserId(userId);
        if (EmptyUtils.isEmpty(query.getGoodsId())) {
            return JsonResult.paramErrWithMsg("参数错误，无效的商品");
        } else {
            welfareUserShoppingCart.setGoodsId(query.getGoodsId());
            welfareUserShoppingCartSelect.setGoodsId(query.getGoodsId());
        }
        if (EmptyUtils.isEmpty(query.getSkuId())) {
            return JsonResult.paramErrWithMsg("参数错误，无效的sku");
        } else {
            welfareUserShoppingCart.setSkuId(query.getSkuId());
            welfareUserShoppingCartSelect.setSkuId(query.getSkuId());
        }
        if (EmptyUtils.isEmpty(query.getQuantity())) {
            return JsonResult.paramErrWithMsg("参数错误，无效数量");
        }
        welfareUserShoppingCart.setCreateTime(new Date());
        WelfareUserShoppingCart welfareUserShoppingCartRes = welfareUserShoppingCartService.selectOne(welfareUserShoppingCartSelect);
        int resCode;
        if (EmptyUtils.isNotEmpty(welfareUserShoppingCartRes)) {
            Integer tempQuantity = welfareUserShoppingCartRes.getQuantity() + query.getQuantity();
            // 不能超过最大数量限制
            if (tempQuantity > MAX_SHOPPING_CART_LIMIT) {
                welfareUserShoppingCartRes.setQuantity(MAX_SHOPPING_CART_LIMIT);
            } else {
                welfareUserShoppingCartRes.setQuantity(welfareUserShoppingCartRes.getQuantity() + query.getQuantity());
            }
            welfareUserShoppingCartRes.setUpdateTime(new Date());
            resCode = welfareUserShoppingCartService.updateByPrimaryKeySelective(welfareUserShoppingCartRes);
        } else {
            welfareUserShoppingCart.setQuantity(query.getQuantity());
            resCode = welfareUserShoppingCartService.insertSelective(welfareUserShoppingCart);
        }
        if (resCode < 1) {
            return JsonResult.failWithMsg("操作失败，请重试");
        }
        return JsonResult.success();
    }

    /**
     * 添加商品到购物车
     * @param query 购物车查询实体类
     * @return com.dzl.util.JsonResult<java.lang.Object>
     * @author ChenLong
     * @since 2021-05-20 15:23:59
     **/
    @PostMapping(value = "addGoodsBuyToCart")
    public JsonResult<WelfareUserShoppingCart> addGoodsBuyToCart(@RequestBody WelfareUserShoppingCartDto query) {
        log.info("addGoodsToCart in query: " + query);
        Integer userId = getWxUserInfo().getId();
        WelfareUserShoppingCart welfareUserShoppingCart = new WelfareUserShoppingCart();
        welfareUserShoppingCart.setUserId(userId);
        if (EmptyUtils.isEmpty(query.getGoodsId())) {
            return JsonResult.paramErrWithMsg("参数错误，无效的商品");
        } else {
            welfareUserShoppingCart.setGoodsId(query.getGoodsId());
        }
        if (EmptyUtils.isEmpty(query.getSkuId())) {
            return JsonResult.paramErrWithMsg("参数错误，无效的sku");
        } else {
            welfareUserShoppingCart.setSkuId(query.getSkuId());
        }
        if (EmptyUtils.isEmpty(query.getQuantity())) {
            return JsonResult.paramErrWithMsg("参数错误，无效数量");
        } else {
            welfareUserShoppingCart.setQuantity(query.getQuantity());
        }
        welfareUserShoppingCart.setCreateTime(new Date());
        welfareUserShoppingCart.setStatus(2);
        if (welfareUserShoppingCartService.insertSelective(welfareUserShoppingCart) < 1) {
            return JsonResult.failWithMsg("操作失败，请重试");
        }
        return JsonResult.success(welfareUserShoppingCart);
    }

    /**
     * 获取用户购物车商品数量
     * @param
     * @return com.dzl.util.JsonResult
     * @author ChenLong
     * @date 2021-06-16 18:29:06
     **/
    @GetMapping(value = "getUserShoppingCartCount")
    public JsonResult<Integer> getUserShoppingCartCount() {
        log.info("getUserShoppingCartCount in query");
        Integer userId = getWxUserInfo().getId();
        WelfareUserShoppingCart welfareUserShoppingCart = new WelfareUserShoppingCart();
        welfareUserShoppingCart.setStatus(1);
        welfareUserShoppingCart.setUserId(userId);
        return JsonResult.success(welfareUserShoppingCartService.selectCount(welfareUserShoppingCart));
    }
}